﻿using System;
using System.ServiceModel;
using System.ServiceModel.Activation;
using Microsoft.Practices.Unity;

namespace Hopscotch.Common.Services.Wcf
{
    public class UnityServiceHostFactory : ServiceHostFactory, IDisposable
    {
        // Track whether Dispose has been called.
        private bool disposed = false;

        private readonly UnityContainer container;
        public UnityServiceHostFactory()
        {
            container = new UnityContainer();
        }

        protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
        {
            UnityServiceHost serviceHost = new UnityServiceHost(serviceType, baseAddresses);
            serviceHost.Container = container;

            return serviceHost;
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                if (disposing && container != null)
                {
                    container.Dispose();
                }

                disposed = true;
            }
        }

        ~UnityServiceHostFactory()
        {
            Dispose(false);
        }
    }
}